package com.clarence.dada.modular.system.role.service.impl;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clarence.dada.core.redis.RedisOperatorApi;
import com.clarence.dada.modular.system.resource.service.SysResourceService;
import com.clarence.dada.modular.system.role.entity.SysRoleResourceEntity;
import com.clarence.dada.modular.system.role.entity.req.SysRoleReq;
import com.clarence.dada.modular.system.role.entity.req.SysRoleResourceReq;
import com.clarence.dada.modular.system.role.mapper.SysRoleResourceMapper;
import com.clarence.dada.modular.system.role.service.SysRoleResourceService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统角色菜单service接口实现类
 *
 * @author majianguo
 * @date 2020/11/5 上午11:32
 */
@Service
public class SysRoleResourceServiceImpl extends ServiceImpl<SysRoleResourceMapper, SysRoleResourceEntity> implements SysRoleResourceService {

    @Resource(name = "roleResourceCacheApi")
    private RedisOperatorApi<List<String>> roleResourceCacheApi;

    @Resource
    private SysResourceService sysResourceService;

//    @Resource
//    private InitConfigApi initConfigApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grantResource(SysRoleReq req) {

        Long roleId = req.getRoleId();

        // 删除所拥有角色关联的资源
        LambdaQueryWrapper<SysRoleResourceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleResourceEntity::getRoleId, roleId);
        this.remove(queryWrapper);

        // 清除角色缓存资源
        roleResourceCacheApi.remove(String.valueOf(roleId));

        // 授权资源
        List<String> codeList = req.getGrantResourceList();
        List<SysRoleResourceReq> list = new ArrayList<>();
        for (String resCode : codeList) {
            SysRoleResourceReq sysRoleResourceReq = new SysRoleResourceReq();
            sysRoleResourceReq.setResourceCode(resCode);
            list.add(sysRoleResourceReq);
        }
        this.batchSaveResCodes(roleId, list);
    }

    @Override
    public void grantResourceV2(SysRoleReq req) {
        // 先将该业务下，模块下的所有资源删除掉
        List<String> modularTotalResource = req.getModularTotalResource();
        if (ObjectUtil.isNotEmpty(modularTotalResource)) {
            LambdaUpdateWrapper<SysRoleResourceEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(SysRoleResourceEntity::getResourceCode, modularTotalResource);
            wrapper.eq(SysRoleResourceEntity::getRoleId, req.getRoleId());
            this.remove(wrapper);
        }

        // 再将该业务下，需要绑定的资源添加上
        List<String> selectedResource = req.getSelectedResource();
        if (ObjectUtil.isNotEmpty(selectedResource)) {
            ArrayList<SysRoleResourceEntity> sysRoleResources = new ArrayList<>();
            for (String resourceCode : selectedResource) {
                SysRoleResourceEntity sysRoleResource = new SysRoleResourceEntity();
                sysRoleResource.setRoleId(req.getRoleId());
                sysRoleResource.setResourceCode(resourceCode);
                sysRoleResources.add(sysRoleResource);
            }
            this.saveBatch(sysRoleResources, sysRoleResources.size());
        }

        // 清除角色绑定的资源缓存
        roleResourceCacheApi.remove(String.valueOf(req.getRoleId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleResourceListByResourceIds(List<Long> resourceIds) {

        // 查询资源包含的角色
        LambdaQueryWrapper<SysRoleResourceEntity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.select(SysRoleResourceEntity::getRoleId);
        wrapper1.in(SysRoleResourceEntity::getResourceCode, resourceIds);
        wrapper1.groupBy(SysRoleResourceEntity::getRoleId);
        List<SysRoleResourceEntity> toGetRoles = this.list(wrapper1);
        List<Long> roleIds = toGetRoles.stream().map(SysRoleResourceEntity::getRoleId).toList();
        for (Long roleId : roleIds) {
            // 清除角色绑定的资源缓存
            roleResourceCacheApi.remove(String.valueOf(roleId));
        }

        // 清除资源
        LambdaQueryWrapper<SysRoleResourceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysRoleResourceEntity::getResourceCode, resourceIds);
        this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleResourceListByRoleId(Long roleId, Integer resourceBizType) {
        LambdaQueryWrapper<SysRoleResourceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleResourceEntity::getRoleId, roleId);
        this.remove(queryWrapper);

        // 清除角色绑定的资源缓存
        roleResourceCacheApi.remove(String.valueOf(roleId));

    }

    @Override
    public void quickSaveAll(List<SysRoleResourceEntity> sysRoleResourceList) {
        List<List<SysRoleResourceEntity>> split = ListUtil.split(sysRoleResourceList, 100);
        for (List<SysRoleResourceEntity> sysRoleResources : split) {
            this.getBaseMapper().insertBatchSomeColumn(sysRoleResources);
        }
    }

    /**
     * 批量保存角色和资源的绑定
     *
     * @author fengshuonan
     * @date 2022/9/29 14:34
     */
    @Override
    public void batchSaveResCodes(Long roleId, List<SysRoleResourceReq> roleResourceReqList) {
        ArrayList<SysRoleResourceEntity> sysRoleResourceList = new ArrayList<>();

        if (ObjectUtil.isNotEmpty(roleResourceReqList)) {
            for (SysRoleResourceReq roleResourceReq : roleResourceReqList) {
                SysRoleResourceEntity sysRoleResource = new SysRoleResourceEntity();
                sysRoleResource.setRoleId(roleId);
                sysRoleResource.setResourceCode(roleResourceReq.getResourceCode());
                sysRoleResourceList.add(sysRoleResource);
            }

            List<List<SysRoleResourceEntity>> split = ListUtil.split(sysRoleResourceList, 100);
            for (List<SysRoleResourceEntity> sysRoleResources : split) {
                this.getBaseMapper().insertBatchSomeColumn(sysRoleResources);
            }
        }
    }

//    @Override
//    public void updateNewAppCode(Boolean decisionFirstStart, String newAppCode) {
//
//        // 判断是否是第一次启动项目
//        if (decisionFirstStart && initConfigApi.getInitConfigFlag()) {
//            return;
//        }
//
//        // 获取所有角色资源表信息
//        List<SysRoleResourceEntity> list = this.list();
//
//        // 批量更新资源编码
//        for (SysRoleResourceEntity sysRoleResource : list) {
//            String newResourceCode = GunsResourceCodeUtil.replace(sysRoleResource.getResourceCode(), newAppCode);
//            sysRoleResource.setResourceCode(newResourceCode);
//        }
//
//        this.updateBatchById(list);
//
//    }

}
